package com.ursu.server.handler;

import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.ursu.client.model.CurrentUser;
import com.ursu.server.dao.UserDao;
import com.ursu.shared.actions.Login;
import com.ursu.shared.actions.LoginResult;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.shared.ActionException;

public class LoginActionHandler implements ActionHandler<Login, LoginResult> {
	
	private final Provider<HttpServletRequest> requestProvider;
	private static final Logger log = Logger.getLogger("LoginActionHandler");

	@Inject
	public LoginActionHandler(final ServletContext servletContext,
		      final Provider<HttpServletRequest> requestProvider) {
		this.requestProvider = requestProvider;
	}

	@Override
	public LoginResult execute(Login action, ExecutionContext context)
			throws ActionException {
		UserDao dao = new UserDao();
		CurrentUser result = null;
		HttpSession session = requestProvider.get().getSession();
		
	    result = dao.loginUser(action.getUsername(), action.getPassword());
			if(result != null)
			{
			
			
			session.setAttribute("login.authenticated", action.getUsername());
			log.severe("\n Username : " + action.getUsername() +" with password: " + action.getPassword()+ " was authenticated!!\n");
			}
		
			return new LoginResult(result);
			
	}

	
	
	
	
	

	@Override
	public void undo(Login action, LoginResult result, ExecutionContext context)
			throws ActionException {
	}

	@Override
	public Class<Login> getActionType() {
		return Login.class;
	}
}
